import struct
import random
import numpy as np
import os

def fp32_to_hex(f):
    """将FP32数值转换为32位十六进制字符串"""
    return f"{np.uint32(f):08X}"

def generate_fp32_case():
    """生成单个FP32测试用例"""
    num_type = random.choice(["normal", "normal", "denormal", "zero", "inf"])
    
    if num_type == "zero":
        sign = random.choice([0, 1])
        return (sign << 31) | 0x00000000
    elif num_type == "inf":
        sign = random.choice([0, 1])
        return (sign << 31) | 0x7F800000
    elif num_type == "denormal":
        sign = random.choice([0, 1])
        mantissa = random.randint(1, 0x007FFFFF)  # 23位尾数
        return (sign << 31) | mantissa
    else:  # normal
        sign = random.choice([0, 1])
        exp = random.randint(1, 0xFE)            # 指数范围1-254
        mantissa = random.randint(0, 0x007FFFFF)  # 23位尾数
        return (sign << 31) | (exp << 23) | mantissa

def fp32_mult(a, b):
    """使用NumPy的FP32乘法"""
    np_a = np.uint32(a).view(np.float32)
    np_b = np.uint32(b).view(np.float32)

    # 处理无穷大
    if np.isinf(np_a) or np.isinf(np_b):
        sign = (a ^ b) & 0x80000000
        return sign | 0x7F800000
    
    # 处理0 × Inf的NaN场景
    if (np_a == 0 and np.isinf(np_b)) or (np.isinf(np_a) and np_b == 0):
        return 0x7FC00000  # 静默NaN
    
    # 正常乘法
    product = np_a * np_b
    return np.uint32(product.view(np.uint32))

# 生成测试用例
test_cases = []
for _ in range(100):
    a = generate_fp32_case()
    b = generate_fp32_case()
    expected = fp32_mult(a, b)
    
    test_cases.append({
        "a": fp32_to_hex(a),
        "b": fp32_to_hex(b),
        "expected": fp32_to_hex(expected)
    })

# 输出到文件
with open("fp32_mult_cases.txt", "w") as f:
    f.write("// FP32乘法测试用例（输入A，输入B，预期结果）\n")
    for case in test_cases:
        f.write(f"{case['a']} {case['b']} {case['expected']}\n")

print("生成100个测试用例到fp32_mult_cases.txt")